package com.vanysoft.business.base.customer.service;

import com.vanysoft.business.base.customer.controller.demo.CustomerDemo;
import com.vanysoft.business.base.team.dao.BaseTeamUsersMapper;
import com.vanysoft.business.base.user.dao.BaseUserMapper;
import com.vanysoft.business.base.user.dao.BaseUserRolesMapper;
import com.vanysoft.business.base.user.dao.BaseUserTagsMapper;
import com.vanysoft.business.base.user.entity.TBaseUser;
import com.vanysoft.business.base.user.entity.TBaseUserTags;
import com.vanysoft.business.base.user.service.BaseUserService;
import com.vanysoft.common.utils.desc.DescUtil;
import com.vanysoft.common.utils.string.StringUtil;
import com.vanysoft.framework.aop.VanySoftAspectException;
import com.vanysoft.framework.constants.DbConstants;
import com.vanysoft.framework.exception.VanySoftBaseException;
import com.vanysoft.framework.messagesource.MessageCodeConstant;
import com.vanysoft.framework.utils.PinYin;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 类名称：BaseCustomerService
 * 类描述：外部人员
 * 创建人：SharpClaw_x
 * 创建时间：2017年5月31日 上午10:56:38
 * 修改人：SharpClaw_x
 * 修改时间：2017年5月31日 上午10:56:38
 * 版本信息：@version 1.0
 * Copyright (c) 2017SharpClaw-版权所有
 * 修改备注：
 */
@Service
@Transactional(readOnly = true)
public class BaseCustomerService {

    @Autowired
    private BaseUserService baseUserService;

    @Autowired
    private BaseUserMapper baseUserMapper;

    @Autowired
    private BaseUserTagsMapper baseUserTagsMapper;

    @Autowired
    private BaseTeamUsersMapper baseTeamUsersMapper;

    @Autowired
    private BaseUserRolesMapper tBaseUserRolesMapper;

    /**
     * Function Name               addCustomer
     *
     * @param user
     * @return
     * @throws VanySoftBaseException
     * @throws VanySoftAspectException
     * @description 添加外部人员
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月31日 下午2:26:44           SharpClaw_x      Initial
     * *********************************************************************
     */
    @Transactional
    public String addCustomer(CustomerDemo user) throws VanySoftAspectException, VanySoftBaseException {
        //检查userCode是否重复
        if (!baseUserService.checkUsercode(user.getUserAccount())) {
            throw new VanySoftAspectException(MessageCodeConstant.UserAndRoleException.RTN_CODE_USER_CODE);
        }
        TBaseUser userEntity = new TBaseUser();

        userEntity.setUserId(UUID.randomUUID().toString());
        userEntity.setUserAccount(user.getUserAccount().trim());
        userEntity.setUserName(user.getUserName());

        String userPassword = DescUtil.encrypt(DbConstants.INIT_PASSWORD + user.getUserAccount() + "_" + user.getUserAccount().length());
        //设置保存密码
        userEntity.setUserPassword(userPassword);
        //头像
        String bgImg = user.getPhoto();

        if (StringUtil.isEmpty(bgImg)) {
            //为空新增默认头像，后续添加
        } else {
            //上传头像
            String appIconPathBody = baseUserService.uploadUserHead(bgImg, user.getUserAccount().trim());

            userEntity.setPhotoUrl(appIconPathBody);
        }
        userEntity.setGender(user.getGender());

        String searchKeyWord1 = PinYin.getPinYinHeadChar(user.getUserName().trim()).toUpperCase();
        //姓名简拼
        userEntity.setSearchKeyWord1(searchKeyWord1);
        //全拼
        String searchKeyWord2 = PinYin.getPingYin(user.getUserName().trim()).toUpperCase();
        userEntity.setSearchKeyWord2(searchKeyWord2);
        userEntity.setTel(user.getQq());
        userEntity.setMobile(user.getMobile());
        userEntity.setIdentificationTypeCode(user.getIdentificationTypeCode());
        userEntity.setIdentificationNo(user.getIdentificationNo());
        userEntity.setEmail(user.getEmail());
        userEntity.setWechat(user.getWechat());
        userEntity.setCompany(user.getCompany());
        userEntity.setDept(user.getCompany());
        userEntity.setJobPosition(user.getJobPosition());
        userEntity.setStatus(DbConstants.IS_AVAILABLE);
        userEntity.setIsCustomer(DbConstants.IS_AVAILABLE);
        userEntity.setUpdateTime(new Date());
        userEntity.setIsAvailable(DbConstants.IS_AVAILABLE);

        baseUserMapper.insertSelective(userEntity);

        if (StringUtils.isNotEmpty(user.getTags())) {
            String[] tagArr = user.getTags().split(",");

            for (String tagCode : tagArr) {
                TBaseUserTags userTag = new TBaseUserTags();
                userTag.setUserTagId(UUID.randomUUID().toString());
                userTag.setUserId(userEntity.getUserId());
                userTag.setTagCode(tagCode);

                baseUserTagsMapper.insert(userTag);
            }

        }

        return MessageCodeConstant.RTN_CODE_SUCCESS;
    }

    @Transactional
    public void addExcelCustomer(List<CustomerDemo> list, String repeatDeal) {

        for (CustomerDemo customer : list) {
            TBaseUser userEntity = new TBaseUser();

            userEntity.setUserId(UUID.randomUUID().toString());
            userEntity.setUserAccount(customer.getUserAccount());
            userEntity.setUserName(customer.getUserName());
            //设置保存密码
            userEntity.setUserPassword(DescUtil.encrypt(DbConstants.INIT_PASSWORD + customer.getUserAccount() + "_" + customer.getUserAccount().length()));

            userEntity.setGender(customer.getGender());
            //姓名简拼
            userEntity.setSearchKeyWord1(PinYin.getPinYinHeadChar(customer.getUserName()).toUpperCase());
            //全拼
            userEntity.setSearchKeyWord2(PinYin.getPingYin(customer.getUserName()).toUpperCase());
            userEntity.setMobile(customer.getMobile());
            userEntity.setEmail(customer.getEmail());
            userEntity.setWechat(customer.getWechat());
            userEntity.setJobPosition(customer.getJobPosition());
            userEntity.setDept(customer.getJobPosition());
            userEntity.setStatus(DbConstants.IS_AVAILABLE);
            //和导入外部人员复用、customer字段由Action定制
            userEntity.setIsCustomer(DbConstants.IS_AVAILABLE);
            userEntity.setUpdateTime(new Date());
            userEntity.setIsAvailable(DbConstants.IS_AVAILABLE);
            //检查userCode是否重复
            TBaseUser userDB = baseUserMapper.selectByUserAccount(userEntity.getUserAccount());
            if (userDB == null) {
                baseUserMapper.insertSelective(userEntity);

                TBaseUserTags userTag = new TBaseUserTags();
                userTag.setUserTagId(UUID.randomUUID().toString());
                userTag.setTagCode(customer.getTags());
                userTag.setUserId(userEntity.getUserId());

                baseUserTagsMapper.insert(userTag);
            } else {
                //userCode如果重复则判断处理条件
                //忽略不做操作
                if (StringUtils.equals(repeatDeal, DbConstants.USER_COVER)) {
                    //覆盖则更新
                    userEntity.setUserId(userDB.getUserId());
                    baseUserMapper.updateByPrimaryKey(userEntity);

                    //删除旧的关系
                    baseTeamUsersMapper.deleteTeamUser(userDB.getUserId());
                    baseUserTagsMapper.deletTagUser(userDB.getUserId());
                    tBaseUserRolesMapper.deletUserRoleByUserId(userDB.getUserId());
                    //添加新的关系
                    TBaseUserTags userTag = new TBaseUserTags();
                    userTag.setUserTagId(UUID.randomUUID().toString());
                    userTag.setTagCode(customer.getTags());
                    userTag.setUserId(userEntity.getUserId());

                    baseUserTagsMapper.insert(userTag);
                }

            }
        }
    }


    /**
     * Function Name               delCustomerBatch
     *
     * @param tagUserIds
     * @description 批量删除外部人员
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月21日 上午11:40:49           SharpClaw_x      Initial
     * *********************************************************************
     */
    @Transactional
    public void delCustomerBatch(String tagUserIds) {
        String[] tagUserArr = tagUserIds.split(",");
        TBaseUser user = null;
        TBaseUserTags userTag = null;
        for (String tagUserId : tagUserArr) {
            userTag = baseUserTagsMapper.selectByPrimaryKey(tagUserId);
            user = baseUserMapper.selectByPrimaryKey(userTag.getUserId());
            if (user != null && user.getIsCustomer().equals(DbConstants.IS_AVAILABLE)) {
                user.setIsAvailable(DbConstants.IS_NOT_AVAILABLE);
                baseUserMapper.updateByPrimaryKey(user);
                baseUserTagsMapper.deleteByPrimaryKey(tagUserId);
            }
        }
    }

}
